package com.defysoft.waukids;

import org.json.JSONObject;

import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class TestActivity extends BaseActivity implements OnClickListener {
	TextView tv;
	ImageView iv;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_test);
		setStartData();
		startNetwork(1);
	}

	@Override
	public void setStartData() {
		tv = (TextView) findViewById(R.id.tv);
		iv = (ImageView) findViewById(R.id.btn);
		iv.setOnClickListener(this);
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case 1:
					mainThread();
					break;
				case 2:
					subThread();
					break;
				}
			}
		});
		firstThread.start();
		startDIal();
	}
	
	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case 0: // 0번은 꼭 try catch의 오류수정코드
			endDIal();
			firstThread.interrupt();
			showPopup("네트워크오류", "네트워크 실패", 0);
			Toast.makeText(this, (String)_message.obj, Toast.LENGTH_LONG).show();
			break;
		case 1: // 1번은 꼭 서버에러코드 출력으로
			endDIal();
			firstThread.interrupt();
			showPopup("로그인 실패", (String) _message.obj, 0);
			break;
		case 2:
			endDIal();
			firstThread.interrupt();
			tv.setText((String) _message.obj);
			break;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn:
			startNetwork(2);
			break;
		}
	}
	//처음이라는 문자띄우는 네트워크 접근
	public void mainThread() { 
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback("http://seo2kt.cafe24.com/apiV3/testpage.php", "param=처음"));
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				onNetworkCallback(2, msg);
			} else {
				onNetworkCallback(1, jsonObject.getString("message"));
			}
		} catch (Exception e) {onNetworkCallback(0, e.toString());
		}
		;
	}

	public void subThread() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback("http://seo2kt.cafe24.com/apiV3/testpage.php", "param=서브"));
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				onNetworkCallback(2, msg);
			} else {
				onNetworkCallback(1, jsonObject.getString("message"));
			}
		} catch (Exception e) {onNetworkCallback(0, e.toString());
		}
		;
	}
}
